var finesse = finesse || {};
finesse.gadget = finesse.gadget || {};
finesse.container = finesse.container || {};

/** @namespace */
// Configuration for the gadget
finesse.gadget.Config = (function () {
	var _prefs = new gadgets.Prefs();

	/** @scope finesse.gadget.Config */
	return {
		authorization: _prefs.getString("authorization"),
		host: _prefs.getString("host"),
		restHost: "localhost"
	};
}());

/** @namespace */
finesse.modules = finesse.modules || {};
finesse.modules.SampleGadget = (function ($) {
    var user, states, dialogs,
    
    /**
     * Populates the fields in the gadget with data
     */
    render = function () {
        var currentState = user.getState();

        
		
		
		console.log("in render in SampleGadget_HubTopic");
    
        
        gadgets.window.adjustHeight();
    },
	

	// Handler to handle changes in a dialog
	_processCall = function (dialog) {
		// dialog.getId();

	},
    
    /**
     *  Handler for additions to the Dialogs collection object.  This will occur when a new
     *  Dialog is created on the Finesse server for this user.
     */
     handleNewDialog = function(dialog) {
         // Get call variables from the dialog
         var callVars = dialog.getMediaProperties();
         
       
		 dialog.addHandler('change', _processCall);
		// _processCall(dialog);
    },
     
    /**
     *  Handler for deletions from the Dialogs collection object for this user.  This will occur
     *  when a Dialog is removed from this user's collection (example, end call)
     */
    handleEndDialog = function(dialog) {
    	
    },
    
    /**
     * Handler for makeCall when successful.
     */
    makeCallSuccess = function(rsp) {

	
    },
    
    /**
     * Handler for makeCall when error occurs.
     */
    makeCallError = function(rsp) {
	
	// document.getElementById('errorMsg').innerHTML = rsp.content;
	document.getElementById('errorMsg').innerHTML = _util.getErrData(rsp);
	// document.getElementById('errorMsg').innerHTML = rsp.object.ApiErrors.ApiError.ErrorMessage;
	
    },
     
    /**
     * Handler for the onLoad of a User object.  This occurs when the User object is initially read
     * from the Finesse server.  Any once only initialization should be done within this function.
     */
    handleUserLoad = function (userevent) {
        // Get an instance of the dialogs collection and register handlers for dialog additions and
        // removals
        dialogs = user.getDialogs( {
            onCollectionAdd : handleNewDialog,
            onCollectionDelete : handleEndDialog
        });
         
        render();
    },
      
    /**
     *  Handler for all User updates
     */
    handleUserChange = function(userevent) {
        render();
   },
	   /**
     * Handler for the dataRequestHandler from a hub.subscribe request.
	 *
	 *
     */
	_dataRequestHandler = function (topic, data) {
        var dataCopy;
         console.log ("In _dataRequestHandler SampleGadget_ErrorH");
        //Ensure a valid data object with "type" and "data" properties.
        if (typeof data === "object" &&
                typeof data.type === "string" &&
                typeof data.data === "object") {
			switch (data.type) {
			case "SendDataReq":
			     // place the text in the 'hubtext' element
			     document.getElementById('hubtext').innerHTML = data.data.text
				
                break;
			
			default:
				break;
			}
		}
        
    };
	
	    
	/** @scope finesse.modules.SampleGadget */
	return {
	   

	

	
		/**
     * Make a SendDataReq request to the our topic.
	 
     * @private
     */
	
		//sets the hub text
		
		setHubText : function () {
		    var text;
		    console.log("in setHubText SampleGadget_ErrorH: " + text);
	        //text = document.getElementById('textfield').innerHTML;
			text = document.getElementById('hubtextin').value;
			if (gadgets.Hub) {
					 console.log ("check gadgets.hub SampleGadget_HubTopic");
                   
                    
                    //makeSendDataReq(text);
					var data = {
				type: "SendDataReq",
				data: { text : text},
				invokeID: (new Date()).getTime()
			};
			console.log ("makeSendDataReq b4 publish SampleGadget_HubTopic");
			gadgets.Hub.publish("sampleGadget.info", data);
			        console.log ("returned from makeSendDataReq SampleGadget_HubTopic");
				}
	    },
	   /**
	     * Sets the user state
	     */
	    setUserState : function (state) {
	        if (state === 'READY') {
	            user.setState(states.READY);
	        } else if (state === 'NOT_READY') {
	            user.setState(states.NOT_READY);
	        }
	    },
		
		
	    
	    /**
	     * Make a call to the number
	     */
	    makeCall : function (number) {
	        // Example of the user make call method
	    	user.makeCall(number, {
	    		success: makeCallSuccess,
	    		error: makeCallError
	    	});
	    	
	    
	    },
	        
	    /**
	     * Performs all initialization for this gadget
	     */
	    init : function () {
			var prefs =  new gadgets.Prefs(),
			id = prefs.getString("id");

	        gadgets.window.adjustHeight();
	        
	        // Initiate the ClientServices and load the user object.  ClientServices are
	        // initialized with a reference to the current configuration.
	        finesse.clientservices.ClientServices.init(finesse.gadget.Config);
	        user = new finesse.restservices.User({
				id: id, 
                onLoad : handleUserLoad,
                onChange : handleUserChange
            });
	            
	        states = finesse.restservices.User.States;
			// subscribe to the hub topic "sampleGadget.info"
			if (gadgets.Hub) {
					// for debugging
					console.log ("check gadgets.hub in SampleGadget_HubTopic");
                    
                    gadgets.Hub.subscribe("sampleGadget.info", _dataRequestHandler);
					console.log ("subscribe to sampleGadget.info in SampleGadget_HubTopic");
					}
	    }
    };
}(jQuery));
